import { Button, ConfigProvider, notification } from 'antd';

import { VariableValueField } from '@/components/base/ValueOfType';
import { BaseNode } from '@/components/complex/BaseNode';
import { defineComponentAndRegisterToGraph } from '@/components/complex/BaseNode/define';
import { NodeDrawer } from '@/components/complex/NodeDrawer';
import { NodeVariableMangerForm } from '@/components/complex/NodeVariableMangerForm';
import { NODE_TYPE } from '@/constants/config';
import { useGraph } from '@/hooks/useGraph';
import { useNodeResults } from '@/store/node-results';
import { fetchOfSSE } from '@/utils/fetch-sse';
import { showNodeStatusWithState } from '@/utils/graph';

import { BlockSetting } from '../../BaseNode/components/BlockSetting';
import { VariablesTable } from '../../VariablesTable';

export const ManualNode = defineComponentAndRegisterToGraph(NODE_TYPE.MANUAL, (props) => {
  let extra = null;
  const { graph } = useGraph();
  const [approveLoading, setApproveLoading] = useState(false);
  const execResultsStore = useNodeResults();
  const targetNodeResult = execResultsStore.resultsOfList.find((item) => item.nodeId === props.node?.id);
  const finalStatus = targetNodeResult?.execStatus;
  const [tempAllPrivateVariables, setTempAllPrivateVariables] = useState<string[]>([]);

  const getPublicVariables = () => {
    const data = graph?.getCellById(props.node?.id!)?.getData();
    const publicVariables = data?.publicVariables || [];
    return publicVariables as VariableItem[];
  };

  const approve = (flowStatus: 'PASS' | 'REJECT') => {
    if (!targetNodeResult) {
      notification.warning({ message: '未找到节点执行结果' });
      return;
    }
    setApproveLoading(true);
    const publicVariables = getPublicVariables();
    const execParams = publicVariables.reduce((acc: Record<string, string>, cur, index) => {
      acc[cur.varName!] = tempAllPrivateVariables[index] || cur.initValue || '';
      return acc;
    }, {});

    setTempAllPrivateVariables([]);

    fetchOfSSE('/flow/resume', {
      method: 'POST',
      body: JSON.stringify({
        flowStatus,
        execParams,
        flowId: targetNodeResult.flowId!,
        nodeId: targetNodeResult.nodeId!,
        execId: targetNodeResult.execId!,
        parentId: targetNodeResult.parentId!
      }),
      headers: {
        'Content-Type': 'application/json'
      },
      onMessage(message) {
        if (message === '[DONE]') {
          setApproveLoading(false);
        }
        try {
          const data = JSON.parse(message);
          if (data) {
            execResultsStore.addResults(data);
            showNodeStatusWithState(graph!, data);
          }
        } catch (error) {}
      }
    });
  };

  if (finalStatus === 'WAITING') {
    const publicVariables = getPublicVariables();
    extra = (
      <div
        key="approve"
        onClick={(e) => e.stopPropagation()}
        className="manual-confirm flex flex-col gap-8 absolute top-48 left-[50%] -translate-x-[50%] w-640 p-12 bg-white rounded-8">
        <div className="text-center text-16--bold">人工审核确认</div>
        {publicVariables.length > 0 && (
          <ConfigProvider componentDisabled={false}>
            <VariablesTable
              dataSource={publicVariables}
              title="参数"
              actions={{
                title: '值',
                key: 'action',
                render: (record, __, index) => {
                  return (
                    <div onMouseMove={(e) => e.stopPropagation()}>
                      <VariableValueField
                        varType={record.varType!}
                        options={record.options || []}
                        value={tempAllPrivateVariables[index] !== undefined ? tempAllPrivateVariables[index] : record.initValue}
                        onChange={(value) => {
                          tempAllPrivateVariables[index] = value;
                          setTempAllPrivateVariables([...tempAllPrivateVariables]);
                        }}
                      />
                    </div>
                  );
                }
              }}
            />
          </ConfigProvider>
        )}
        <div className="flex justify-center pt-12 gap-12">
          <Button disabled={false} loading={approveLoading} onClick={() => approve('REJECT')} type="default">
            <span className="text-14 text-red-500">拒绝</span>
          </Button>
          <Button disabled={false} loading={approveLoading} onClick={() => approve('PASS')} type="primary">
            通过
          </Button>
        </div>
      </div>
    );
  }

  return (
    <NodeDrawer trigger={<BaseNode {...props} nodeType={NODE_TYPE.MANUAL} extra={extra} />}>
      <BlockSetting className="mb-12" />
      <NodeVariableMangerForm type="public" title="人工确认参数变量" />
    </NodeDrawer>
  );
});

ManualNode.displayName = 'ManualNode';
